package com.ext.portlet.pruebastruts.dao.mysql;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DaoLibro {

	static DaoLibro __instance = null;
	
	public static DaoLibro getInstance()
	{
		if (__instance == null)
			__instance = new DaoLibro();
		return __instance;
	}
	
	private DaoLibro()
	{
		try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } 
		catch (Exception ex) {
        	System.out.println("Error en DaoLibro.getConnection :" + ex.getMessage());
        }
	}
	
	private Connection getConnection()
	{
		Connection conn = null;
		try
		{
			conn = DriverManager.getConnection("jdbc:mysql://localhost/pruebastruts?" + 
                    "user=root&password=root");
		}
		catch (SQLException e)
		{
			System.out.println("Error en DaoLibro.getConnection :" + e.getMessage());
		}
		return conn;
	}
	
	public void AddLibro(String nombre)
	{
		Statement stmt = null;
		try {
		    Connection conn = this.getConnection();
			stmt = conn.createStatement();
		    stmt.execute("INSERT INTO LIBROS (NOMBRE) VALUES ('"+nombre+"')");
		} 
		catch (SQLException ex)
		{
			System.out.println("Error en DaoLibro.AddLibro :" + ex.getMessage());
		}
		finally {
		    if (stmt != null) {
		        try {
		            stmt.close();
		        } 
		        catch (SQLException sqlEx) 
		        { }
		        stmt = null;
		    }
		}
	}
	
	public List<String> GetLibros()
	{
		Statement stmt = null;
		ResultSet rs = null;
		List<String> losLibros = new ArrayList<String>();
		try {
		    Connection conn = this.getConnection();
			stmt = conn.createStatement();
		    rs = stmt.executeQuery("SELECT * FROM LIBROS");
		    while (rs.next())
		    {
		    	String libro = rs.getString(1);
		    	losLibros.add(libro);
		    }
		} 
		catch (SQLException ex){
			System.out.println("Error en DaoLibro.AddLibro :" + ex.getMessage());
		}
		finally {
			if (rs != null) {
		        try {
		            rs.close();
		        } catch (SQLException sqlEx) { }
		        rs = null;
		    }
			if (stmt != null) {
		        try {
		            stmt.close();
		        } catch (SQLException sqlEx) { }
		        stmt = null;
		    }
		}
		return losLibros;
	}

}
